package com.emag;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.StartTag;
import net.htmlparser.jericho.Tag;

import com.http.HttpCl;
import com.model.Pret;
import com.model.Product;
import com.store.StoreH2Hib;



public class Emag {

	private static String SiteName = "emag";
	private String _url = "";
	private int _pageNo = 0;
	private HttpCl _http;
	private StoreH2Hib _dbManager;
	
	public Emag()
	{
		//init http client
		_http = new HttpCl();
        
        //open database for store data
        _dbManager = new StoreH2Hib();
		_dbManager.open("/home/vlad/h2.db");
	}
	
	public void execSearch(String _url)
	{
		
		InputStream requestResult = _http.execRequest(_url);
		Source _source = null;
		
		try {
			_source = new Source(requestResult);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		_source.setLogger(null);
		
		//main
		_pageNo++;
		//System.out.println("Pagina: "+_pageNo);
		this.insertProdus(_source);
	}
	
	//------------------------------- extras nume si pret -----------------------------------------
	
	private void insertProdus(Source _source)
	{
		Element pr = _source.getElementById("products-holder");
		List<StartTag> el_title = pr.getAllStartTagsByClass("col-2-prod");
		List<StartTag> el_pret = pr.getAllStartTagsByClass("col-3-prod");
		long startTime = System.currentTimeMillis();
		for (int i=0;i<el_title.size();i++)
		{
			String descr = this.getProdDescription(el_title.get(i));
			//prepare product and pret
			Product _produs = this.TV(descr);
			_produs.setSite(Emag.SiteName);
			Pret _pret = new Pret();
			_pret.setPret(this.getPret(el_pret.get(i)));
			_produs.addPret(_pret);//implementeaza adaugarea incrucisata
			//check if product exista deja
			Product existingProduct = _dbManager.findByDescription(_produs.getDescriere());
			if(existingProduct == null)
			{
				_dbManager.InsertProduct(_produs);
			}else{
				existingProduct.addPret(_pret);
				_dbManager.addPretProduct(existingProduct);
			}
				
		}
		long endTime = System.currentTimeMillis();
		System.out.println(endTime-startTime);
		//go to next page if avaible
		_url = this.getNextPage(_source);
		if(_url != null)
		{
			//baga un delay ca sa nu ii stresam prea tare
			//Thread.sleep(5000);
			this.execSearch(_url);
		}else{
			System.out.println("finish!");
			_dbManager.close();
			//_wtf.closeFile();
		}
	}
	
	private String getProdDescription(StartTag st)
	{
		Tag mytag = st.getNextTag().getNextTag();//este div -> h2 -> a. Am 2 nextTag ca sa ajung la <a>
		String nume_produs = mytag.getElement().getAttributeValue("title").trim().toLowerCase();
		return nume_produs;
	}
	
	private Product TV(String str)
	{
		//cleanup
		str = str.split("-cadou")[0];
		//begin
		Product pr = new Product();
		//string model: "Televizor LED Samsung, 101cm, FullHD, 40D5003";
		String part = str.substring(0, str.indexOf(","));
		String categorie = part.substring(0, part.indexOf(" "));
		String marca = part.substring(part.lastIndexOf(" ")+1);
		
		pr.setMarca(marca);
		pr.setCategorie(categorie);
		pr.setDescriere(str);
		return pr;
	}
	
	private Double getPret(StartTag st)
	{
		Element pret = st.getElement();
		StartTag st_pret;
		StartTag st_pret_decimal;
		//E posibil sa avem doua preturi, unul nou si unul dupa reducere
		List<StartTag> l = pret.getAllStartTagsByClass("money-int");
		List<StartTag> d = pret.getAllStartTagsByClass("money-decimal");
		if(l.size()==2)
		{
			//se ia a doua varianta, pretul nou
			st_pret = l.get(1);
			st_pret_decimal = d.get(1);
		}else{
			//se ia singura varianta, pretul fara reducere
			st_pret = l.get(0);
			st_pret_decimal = d.get(0);
		}
		String pretIntreg = st_pret.getElement().getContent().toString().trim().replace(".", "");
		String pretZecimal = st_pret_decimal.getElement().getContent().toString().trim();
		String pretFinal = pretIntreg+"."+pretZecimal;
		
		return new Double(pretFinal);
	}
	//------------------------------------- extras pagini -----------------------------------------
	
	private String getNextPage(Source _source)
	{
		String _myurl = null;
		//se navigheaza pe noduri. destul de aiurea
		List<Element> e1 = _source.getAllElementsByClass("content-with-sidebar");
		Element _e1 = e1.get(0);
		List<Element> e2 = _e1.getAllElementsByClass("products-pagination");
		Element _e2 = e2.get(0);
		List<Element> e3 = _e2.getAllElementsByClass("holder-pagini-2");
		Element _pg = e3.get(0);
		List<Element> pages= _pg.getAllElementsByClass("pagini-options-2");
		
		//rutina get next page
		//daca span este ultimul tag, atunci suntem la ultima pagina
		//altfel, luam urmatoarea pagina dupa tagul span
		if(!pages.isEmpty())
		{
			int i = 0;
			for (Element temp : pages)
			{
				if(temp.getStartTag().getName() == HTMLElementName.SPAN)
				{
					if(pages.size()-1 > i)
					{
						//here is next page
						_myurl = "http://www.emag.ro"+pages.get(i+1).getAttributeValue("href").toString();
					}
					break;
				}
				//nu am gasit inca span. Continua iterarea
				i++;
			}
			return _myurl;
		}else{
			System.out.println("no pages");
			return null;
		}
	}
	
	
			
}
